package com.etennis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.etennis.mapper.CommodityMapper;
import com.etennis.mapper.MemberMapper;
import com.etennis.mapper.OrderMapper;
import com.etennis.pojos.PageResult;
import com.etennis.pojos.dto.web.ExchangePageQueryDTO;
import com.etennis.pojos.entity.Commodity;
import com.etennis.pojos.entity.Member;
import com.etennis.pojos.entity.Order;
import com.etennis.pojos.vo.web.ExchangeVO;
import com.etennis.service.IOrderService;
import com.etennis.util.SecurityUtils;
import com.etennis.utils.BeanCopyUtils;
import com.etennis.utils.PageUtil;
import com.sun.org.apache.xpath.internal.operations.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    CommodityMapper commodityMapper;
    @Autowired
    MemberMapper memberMapper;

    @Override
    public PageResult<ExchangeVO> pageCode(ExchangePageQueryDTO exchangePageQueryDTO) {
        Page page = PageUtil.convert(exchangePageQueryDTO);
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<Order>().eq(exchangePageQueryDTO.getCode() != null, Order::getCode, exchangePageQueryDTO.getCode());
        Page<Order> orderPage = orderMapper.selectPage(page, wrapper);
        PageResult<ExchangeVO> res = PageUtil.convert(orderPage, each -> {
            ExchangeVO exchangeVO = BeanCopyUtils.copyBean(each, ExchangeVO.class);
            Commodity commodity = commodityMapper.selectById(each.getCommodityId());
            exchangeVO.setCommodityName(commodity.getName());
            exchangeVO.setCommodityPrice(commodity.getPrice());
            Member member = memberMapper.selectById(each.getMemberId());
            exchangeVO.setMemberName(member.getName());
            return exchangeVO;
        });
        return res;
    }

    /**
     * 兑换兑换码
     * @param orderId
     */
    @Override
    @Transactional
    public void stats(Long orderId) {
        Order order = orderMapper.selectById(orderId);

        // 扣减商品余量
        Commodity commodity=commodityMapper.selectById(order.getCommodityId());
        commodity.setRestNum(commodity.getRestNum()-1);
        commodityMapper.updateById(commodity);

//        // 扣减用户积分
//        Member member=memberMapper.selectById(order.getMemberId());
//        member.setScore(member.getScore()-commodity.getPrice());
//        memberMapper.updateById(member);

        // 设置兑换状态
        order.setFlag("0");
        orderMapper.updateById(order);

    }
}
